<template>
  <iframe v-if="iframeSrc" class="iframe" ref="iframe" :src="iframeSrc" frameborder="0"></iframe>
</template>

<script>
// 内嵌跨端组件
import { openPlatformWindow, getPlatformComponentsPath } from "../../util/util";

export default {
  props: {
    src: {
      type: String,
      required: true,
      remark:
        "跳转地址 复制#号之后的部分、如果是静态地址，请加上&prefix拼接在其他参数之前"
    }
  },
  data() {
    return {
      iframeSrc: "",
      prefix: false
    };
  },
  watch: {
    src: {
      handler: "getUrlPath",
      immediate: true
    }
  },
  methods: {
    getQueryKey() {
      let params = [];
      for (const key in this.$route.query) {
        if (key === "prefix") this.prefix = this.$route.query[key];
        else if (key === "name" || key === "src") continue;
        else params.push(key + "=" + this.$route.query[key]);
      }
      if (this.$route.query.src.indexOf("?") > -1) {
        var src = this.$route.query.src;
        var index = src.indexOf("?") + 1;
        this.$route.query.src =
          src.substring(0, index) +
          src.substring(index, src.length).replaceAll("?", "&");
        return this.$route.query.src + "&" + params.join("&");
      } else {
        return (
          this.$route.query.src +
          (params.length > 0 ? "?" : "") +
          params.join("&")
        );
      }
    },
    getUrlPath() {
      const urlParam = this.src === "urlPath" ? this.getQueryKey() : this.src;
      let src = "";
      try {
        src = openPlatformWindow(urlParam, !this.prefix, this.prefix, true);
      } catch (error) {
        console.error(this.$t("parseRouter.noRouter"), error);
        this.$message({
          message: this.$t("parseRouter.noRouter"),
          type: "error"
        });
      }
      const _that = this;
      if (src) {
        this.iframeSrc = src.replace(urlParam, "/components-" + urlParam);
        this.$nextTick(() => {
          const that = this;
          this.$refs.iframe.onload = () => {
            that.$refs.iframe.contentWindow.document
              .getElementById("app")
              .setAttribute("class", "main");
            that.$refs.iframe.contentWindow.document.getElementById(
              "app"
            ).style.overflow = "auto";
          };
        });
        window.addEventListener("message", eve => {
          const data = eve.data;
          if (data.prefix && data.router)
            getPlatformComponentsPath(
              _that.$router,
              `${data.router}&prefix=${data.prefix}&name=${data.name}`
            );
        });
      } else {
        console.error(this.$t("parseRouter.noRouter"));
        this.$message({
          message: this.$t("parseRouter.noRouter"),
          type: "error"
        });
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.iframe {
  width: 100%;
  height: 100%;
  border: 0;
}
/deep/ #app {
  overflow: auto;
}
</style>
